package com.atguigu.chapter07.D02_WaterMark;

import com.atguigu.bean.WaterSensor;
import com.atguigu.util.AnqclnUtil;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * Author: Pepsi
 * Date: 2023/8/5
 * Desc:
 *
 * 进入哪个窗口看事件事件
 * 窗口啥时候关闭看水印 [)  前闭后开
 *
 * 水印可以解决数据的乱序问题
 *
 */
public class Flink02_WaterMark_MyWatermark {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        // 设置水印生成的周期   水印两秒生成一次
        env.getConfig().setAutoWatermarkInterval(2000);

        env
                .socketTextStream("hadoop101",9999)
                .map(line->{
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                // 加水印  分配时间戳和水印
                .assignTimestampsAndWatermarks(
                        // 自定义水印生成器
                        new WatermarkStrategy<WaterSensor>() {
                            @Override
                            public WatermarkGenerator<WaterSensor> createWatermarkGenerator(
                                    WatermarkGeneratorSupplier.Context context) {
                                return new MyWatermarkGenerator();
                            }
                        }
                        // 指明时间戳怎么来
                        .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                            @Override
                            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                return element.getTs();
                            }
                        })
                )
                .keyBy(WaterSensor::getId)
                //  用滚动的事件窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        List<WaterSensor> list = AnqclnUtil.toList(elements);
                        String startTime = AnqclnUtil.toDateTime(context.window().getStart());
                        String endTime = AnqclnUtil.toDateTime(context.window().getEnd());
                        out.collect(s+" "+startTime+" "+endTime+" "+list);
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 自定义一个水印生成器
    private static class MyWatermarkGenerator implements WatermarkGenerator<WaterSensor> {

        // 最大时间戳的默认值， long的最小值加上乱序程度再加一
        long maxTs = Long.MIN_VALUE + 3000 +1;

        // 每来一条数据执行一次
        @Override
        public void onEvent(WaterSensor event, long eventTimestamp, WatermarkOutput output) {
            System.out.println("MyWatermarkGenerator.onEvent");

            // 求最大时间戳     用原来最大的时间戳和新来的这个数据的时间戳做对比
            maxTs = Math.max(maxTs,eventTimestamp);
            output.emitWatermark(new Watermark(maxTs - 3000));   // 打点式/间歇性
        }
        // 周期性的执行，默认是 200ms执行一次
        @Override
        public void onPeriodicEmit(WatermarkOutput output) {
            System.out.println("MyWatermarkGenerator.onPeriodicEmit");

            // 周期性的计算水印
//            output.emitWatermark(new Watermark(maxTs - 3000));
        }
    }
}
